package com.example.customer;

import cn.hutool.core.lang.Validator;
import com.example.client.FraudService;           // 修改的import
import com.example.client.FraudReviewResponse;    // 新增的import
import com.example.customer.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
@Slf4j
public record CustomerService(CustomerRepository customerRepository,
                              FraudService fraudService) {

    public String registerCustomer(CustomerRegistryRequest request) {
        // 利用上面的参数构造一个Customer对象
        Customer customer = Customer.builder()
                .name(request.name())
                .email(request.email())
                .build();

        // 检查email是否有效
        if (request.email()==null|| !Validator.isEmail(request.email())) {
            log.error("new customer registration: email地址无效");
        }
        // 检查email是否已经注册
        // 提示：先思考如何编写sql，再考虑CustomerRepository中如何实现
        Optional<Customer> existEmail = customerRepository.findByEmail(customer.getEmail());

        // 修改的调用代码
        FraudReviewResponse fraudReviewResponse = fraudService.isFraudster(customer.getEmail());
        if (fraudReviewResponse.isFraudster()) {
            throw new ApiException("用户存在征信问题");
        } else {
            // 存入数据库
            customerRepository.saveAndFlush(customer);
            // 发送通知
            log.info("new customer registration: 注册成功 {}", customer);
            return "注册成功";
        }
    }
}